﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using sgsBase;

namespace CreateClass
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string path = Application.ExecutablePath;
            path = path.ToLower().Replace("createclass.exe", "");
            //BaseStaticData.PhysicalPath = path;

			string[] strs =  ApplicationHelper.ConnectionStrings();
			foreach(string dbc in strs)
			{
				comboBox1.Items.Add(dbc);
			}
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            appClassGen acg = new appClassGen();
			acg.Namespace = "h_DbClasses." + comboBox1.SelectedItem.ToString();
			acg.Database = comboBox1.SelectedItem.ToString();
			txResults.Text = acg.genClass(listBox1.Text, txClass.Text);
        }

		private void button2_Click(object sender, EventArgs e)
		{
			string clip = txResults.Text;
			Clipboard.SetText(clip);
		}

		private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (comboBox1.SelectedItem.ToString() == "")
				return;

			string sql; // = "select name from sys.all_objects where (type_desc='USER_TABLE' or type_desc='VIEW') and schema_id=1 order by 1";
			sql = @"select s.name [schema], a.name, a.type
from sys.all_objects a
inner join sys.schemas s on a.schema_id=s.schema_id
where (type='U' or type='V')  and a.schema_id not in (4, 3)
order by 2";

			DbInterface dbi = new DbInterface(comboBox1.SelectedItem.ToString());

			listBox1.DataSource = null;
			listBox1.Items.Clear();

			//listBox1.DataSource = dbi.Query(sql);
			//listBox1.DisplayMember = "name";

			DataTable dt = dbi.Query(sql);
			string str;
			foreach (DataRow dr in dt.Rows)
			{
				str = dr["type"].ToString().Trim() + "." + dr["schema"].ToString() + "." + dr["name"].ToString();
				listBox1.Items.Add(str);
			}
		}

		private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
		{
			string str = listBox1.Text;
			string[] ra = str.Split('.');

			txTable.Text = ra[2]; // listBox1.Text;

			string[] pieces = txTable.Text.Split('_');

			txClass.Text = "Db";
			for (int x = 0; x < pieces.Length; x++)
			{
				if (pieces[x] != "")
					txClass.Text += char.ToUpper(pieces[x][0]) + pieces[x].Substring(1);
			}
			txClass.Text = txClass.Text.Trim('s');
		}

	}
}
